package wxpay

import (
	"crypto/rsa"
	"crypto/x509"
	"encoding/json"
	"errors"
	"fmt"
	"time"
)

type MidWxApp struct {
	WxPayMid
}

func NewMidWxApp(mchid, appid, mch_api_key string, pem_cert *x509.Certificate, pem_key *rsa.PrivateKey) *MidWxApp {
	ent := &MidWxApp{}
	ent.Appid = appid
	ent.Mchid = mchid
	ent.MchAPIKey = mch_api_key
	ent.MchPrivateKey = pem_key
	ent.MchCertificate = pem_cert
	return ent
}

//支付统一下单
//data:支付订单信息
//sub_mch_id:子商户号
func (ent *MidWxApp) CreateOrder(data WxAppOrderData) (WxAppPayParam, error)  {
	var preq WxAppOrderCreateReq
	preq.Sp_appid = ent.Appid
	preq.Sp_mchid = ent.Mchid
	preq.WxAppOrderData = data
	preq.Appid = ""
	preq.Mchid = ""
	preq.WxAppOrderData.Payer.Openid = ""
	data_body, _ := json.Marshal(preq)

	var param_ent WxAppPayParam
	var pret WxAppOrderCreateRet
	const url = "https://api.mch.weixin.qq.com/v3/pay/partner/transactions/jsapi"
	result, err := WxPayPostV3(&ent.MchParam, url, data_body)
	if err != nil {
		return param_ent, err
	}
	err = json.Unmarshal([]byte(result), &pret)
	if err != nil {
		fmt.Println(err)
		return param_ent, err
	}
	if pret.Prepay_id == "" {
		return param_ent, errors.New(pret.Return_msg)
	}

	//小程序客户端支付参数
	param_ent.Appid = preq.Sub_appid
	param_ent.TimeStamp = fmt.Sprintf("%d", time.Now().Unix())
	param_ent.NonceStr, _= GenerateNonce()
	param_ent.Prepay_id = pret.Prepay_id
	param_ent.Package = "prepay_id=" + pret.Prepay_id
	param_ent.SignType = "RSA"
	param_ent.PaySign, _ = param_ent.GenPaySignV3(ent.MchPrivateKey)
	return param_ent, nil
}
